(function() {

  var canvas = document.querySelector('#paint');
  var ctx = canvas.getContext('2d');

  var CurrrentImg = '';

  //TODO=================图片列表点击添加到大容器开始=============
  $(".lists img").click(function(e) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    $("#messageInfo div").html('');
    canvas.width = parseInt(sketch_style.getPropertyValue('width'));
    canvas.height = parseInt(sketch_style.getPropertyValue('height'));
    var currentEm = $(e.target).parent().parent().parent();
    var cloneItem = $(currentEm).clone();
    $(cloneItem).attr("id", "item0");
    var cloneAttrId = $(cloneItem).attr("id", "item0");
    $(cloneAttrId).find(".icon-prev").attr("href", "#item0");
    $(cloneAttrId).find(".icon-next").attr("href", "#item0");
    $(".big #con").empty();
    //$(".contain .lists").remove();
    $(cloneAttrId).appendTo($("#con"));

    var Currrent=$("#item0 .active img").attr("src");
    origin_points = [];
    for (var i in imgInfosList) {
      if (imgInfosList[i].src == Currrent) {
        var CurrrentDesc = imgInfosList[i].pointInfos.originPoints;
        for (var v in CurrrentDesc) {
          var newDiv = document.createElement("div");
          $(newDiv).html(CurrrentDesc[v].desc);
          $(newDiv).appendTo($("#messageInfo"));
        }
        var curent_points = imgInfosList[i].pointInfos.originPoints;
        for (var i in curent_points) {
          origin_points.push(curent_points[i].point);
        }
      }
    }
    appearOriginPoints();

    var LeftBtn = document.querySelector('#item0 .icon-prev');
    var RightBtn = document.querySelector('#item0 .icon-next');
    //单击按钮清楚画布
    LeftBtn.addEventListener('click', function(e) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    });
    RightBtn.addEventListener('click', function(e) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    })
    //TODO  ======切换的时候找到相应的路径===========
    $('#item0').on('slid.bs.carousel', function() {
      ctx.clearRect(0, 0, tmp_canvas.width, tmp_canvas.height);
      $("#messageInfo").empty();
      $("#Text").val("");
      canvas.width = parseInt(sketch_style.getPropertyValue('width'));
      canvas.height = parseInt(sketch_style.getPropertyValue('height'));
      var Currrent = $(this).children().children(".active").children().attr('src')
      origin_points = [];
      for (var i in imgInfosList) {
        if (imgInfosList[i].src == Currrent) {
          var CurrrentDesc = imgInfosList[i].pointInfos.originPoints;
          for (var v in CurrrentDesc) {
            var newDiv = document.createElement("div");
            $(newDiv).html(CurrrentDesc[v].desc);
            $(newDiv).appendTo($("#messageInfo"));
          }
          var curent_points = imgInfosList[i].pointInfos.originPoints;
          console.log(curent_points);
          console.log(imgInfosList);
          for (var i in curent_points) {
            origin_points.push(curent_points[i].point);
          }
        }
      }
      appearOriginPoints();
    });
  });
  //TODO=================图片列表点击添加到大容器结束=============

  var sketch = document.querySelector('#sketch');
  var sketch_style = getComputedStyle(sketch);
  canvas.width = parseInt(sketch_style.getPropertyValue('width'));
  canvas.height = parseInt(sketch_style.getPropertyValue('height'));

  // Determine Tool
  var tool = 'pencil';
  //画图
  document.querySelector('#pencil').onchange = function() {
    if (this.checked)
      tool = 'pencil';

    // Show Tmp Canvas
    tmp_canvas.style.display = 'block';
  };
  //橡皮擦
  document.querySelector('#eraser').onchange = function() {
    if (this.checked)
      tool = 'eraser';

    // Hide Tmp Canvas
    tmp_canvas.style.display = 'none';
  };

  // Creating a tmp canvas
  var tmp_canvas = document.createElement('canvas');
  var tmp_ctx = tmp_canvas.getContext('2d');
  tmp_canvas.id = 'tmp_canvas';
  tmp_canvas.width = canvas.width;
  tmp_canvas.height = canvas.height;

  sketch.appendChild(tmp_canvas);

  var mouse = {
    x: 0,
    y: 0
  }; //起始鼠标位置，也就是mousedown
  var last_mouse = {
    x: 0,
    y: 0
  };

  // Pencil Points
  var ppts = [];

  /* Mouse Capturing Work */
  //通过canvas.addEventListener使画板canvas监听到鼠标事件
  tmp_canvas.addEventListener('mousemove', function(e) {
    mouse.x = typeof e.offsetX !== 'undefined'
      ? e.offsetX
      : e.layerX;
    mouse.y = typeof e.offsetY !== 'undefined'
      ? e.offsetY
      : e.layerY;
  }, false);

  canvas.addEventListener('mousemove', function(e) {
    mouse.x = typeof e.offsetX !== 'undefined'
      ? e.offsetX
      : e.layerX;
    mouse.y = typeof e.offsetY !== 'undefined'
      ? e.offsetY
      : e.layerY;
  }, false);

  /* Drawing on Paint App */
  tmp_ctx.lineWidth = 2;
  tmp_ctx.lineJoin = 'round';
  tmp_ctx.lineCap = 'round';
  tmp_ctx.strokeStyle = 'red';
  tmp_ctx.fillStyle = 'red';
  tmp_canvas.addEventListener('mousedown', function(e) {
    tmp_canvas.addEventListener('mousemove', onPaint, false);

    mouse.x = typeof e.offsetX !== 'undefined'
      ? e.offsetX
      : e.layerX;
    mouse.y = typeof e.offsetY !== 'undefined'
      ? e.offsetY
      : e.layerY;

    ppts.push({x: mouse.x, y: mouse.y});
    onPaint();
  }, false);

  //生成点信息
  function PointInfos() {
    this.id,
    this.point = [],
    this.desc = ''
  }
  //构造图片信息集合函数
  function ImgInfos() {
    this.id = '',
    this.src = '',
    this.pointInfos = [],
    this.pointInfos = {
      originPoints: [],
      transparentPoints: []
    }
  }
  var pps = [];
  var imgInfosList = [];
  ///===========单击按钮================
  //切换时执行的
  $('#item0').on('slide.bs.carousel', function() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    canvas.width = parseInt(sketch_style.getPropertyValue('width'));
    canvas.height = parseInt(sketch_style.getPropertyValue('height'));
  });
  ///===========画完以后================
  tmp_canvas.addEventListener('mouseup', function(e) {
    CurrrentImgSrc = $("canvas").siblings(".tem").find(".active img").attr("src");
    //TODO
    //1,从imgInfosList中循环遍历，发现有无对应的ImgInfo
    //2, 如果没有，新new 一个ImgInfo,然后将图片信息和坐标信息存储到ImgInfo,然后将ImgInfo存储到imgInfosList中
    //3, 如果有ImgInfo，读取ImgInfo,将坐标信息存储到ImgInfo的pointInfoList里去，然后将ImgInfo再存储到imgInfosList
    //保存备注信息
    // 1.每次绘制完以后生成id，ok
    // 2.获得输入框为其添加一个自定义属性与路径的id关联  ok
    // 3.清空输入框，点击把输入框里的内容存到pointInfo里。
    var org_imgInfo;
    for (var i in imgInfosList) {
      if (imgInfosList[i].src == CurrrentImgSrc) {
        org_imgInfo = imgInfosList[i];
      }
    }
    //当前图片没有路径
    if (org_imgInfo == null) {
      var imgInfos = new ImgInfos();
      var pointInfo = new PointInfos();
      pointInfo.point = ppts;
      pointInfo.id = parseInt((pointInfo.point[0].x + pointInfo.point[0].y) / 2);
      $("#Text").attr("data-id", pointInfo.id);
      var allNumber = CurrrentImgSrc.match(/\d/g);
      var id = allNumber.join().replace(',', "");
      imgInfos.id = id;
      imgInfos.src = CurrrentImgSrc;
      imgInfos.pointInfos.originPoints.push(pointInfo);
      imgInfosList.push(imgInfos);
      //TODO 根据2进行编程
    } else {
      //TODO 根据3进行编程
      var pointInfo = new PointInfos();
      pointInfo.point = ppts;
      pointInfo.id = parseInt((pointInfo.point[0].x + pointInfo.point[0].y) / 2);
      $("#Text").attr("data-id", pointInfo.id);
      org_imgInfo.pointInfos.originPoints.push(pointInfo);
    }

    $("#save").click(function() {
      for (var i in imgInfosList) {
        for (var j in imgInfosList[i].pointInfos.originPoints) {
          if (imgInfosList[i].pointInfos.originPoints[j].id == $("#Text").attr("data-id")) {
            var comments = $("#Text").val();
            imgInfosList[i].pointInfos.originPoints[j].desc = comments;
            //  imgInfos.pointInfos.originPoints.push(pointInfo);
            $("#Text").removeAttr("data-id");
            $("#Text").val('');
            newDiv = document.createElement('div');
            $(newDiv).html(comments);
            $(newDiv).appendTo($("#messageInfo"));
          }
        }

      }
    });
    tmp_canvas.removeEventListener('mousemove', onPaint, false);

    //新的颜色覆盖之前的
    ctx.globalCompositeOperation = 'source-over';
    // Writing down to real canvas now
    ctx.drawImage(tmp_canvas, 0, 0);

    // Clearing tmp canvas
    tmp_ctx.clearRect(0, 0, tmp_canvas.width, tmp_canvas.height);
    ppts = [];
  }, false);
  //================画笔==============
  var onPaint = function() {
    // Saving all the points in an array
    ppts.push({x: mouse.x, y: mouse.y});
    if (ppts.length < 3) {
      var b = ppts[0];
      tmp_ctx.beginPath();
      //ctx.moveTo(b.x, b.y);
      //ctx.lineTo(b.x+50, b.y+50);
      tmp_ctx.arc(b.x, b.y, tmp_ctx.lineWidth / 2, 0, Math.PI * 2, !0);
      tmp_ctx.fill();
      tmp_ctx.closePath();
      return;
    }
    // Tmp canvas is always cleared up before drawing.
    //可以消除齿痕
    tmp_ctx.clearRect(0, 0, tmp_canvas.width, tmp_canvas.height);

    tmp_ctx.beginPath();
    tmp_ctx.globalCompositeOperation = 'source-over';
    tmp_ctx.moveTo(ppts[0].x, ppts[0].y); //使用beginPath和moveTo来定义起始点

    for (var i = 1; i < ppts.length - 2; i++) {
      var c = (ppts[i].x + ppts[i + 1].x) / 2;
      var d = (ppts[i].y + ppts[i + 1].y) / 2;
      tmp_ctx.quadraticCurveTo(ppts[i].x, ppts[i].y, c, d); //二次贝赛曲线
    }
    // For the last 2 points
    tmp_ctx.quadraticCurveTo(ppts[i].x, ppts[i].y, ppts[i + 1].x, ppts[i + 1].y);

    tmp_ctx.stroke(); //这时，图形才实际绘制到canvas上去，stroke是绘制图形的边框

  };

  canvas.addEventListener('mousedown', function(e) {
    canvas.addEventListener('mousemove', onErase, false);

    mouse.x = typeof e.offsetX !== 'undefined'
      ? e.offsetX
      : e.layerX;
    mouse.y = typeof e.offsetY !== 'undefined'
      ? e.offsetY
      : e.layerY;

    ppts.push({x: mouse.x, y: mouse.y});
    onErase();
  }, false);

  var ereasers = [];
  var transparent_Points = [];
  var origin_points = [];
  var ereasers_New = [];
  var assa = [];
  var newPoints = [];
  newPoints.push(assa);

  canvas.addEventListener('mouseup', function() {
    ereasers.push(ppts);
    // console.log(imgInfosList);
    // console.log(ereasers);
    var currrentImgSrc = $("#item0 .active img").attr("src");
    for (var i in imgInfosList) {
      // console.log(imgInfosList[i])
      if (imgInfosList[i].src == currrentImgSrc) {
        // console.log(1);
        var curent_points = imgInfosList[i].pointInfos.originPoints;
        for (var i in curent_points) {
          // console.log(curent_points[i].point);
          origin_points.push(curent_points[i].point);
        }
      }
    }
    // console.log(origin_points); //得到当前路径的二维数组

    // console.log(ereasers);
    for (var i in ereasers) {
      for (var j in ereasers[i]) {
        ereasers_New.push(ereasers[i][j]);
        // ereasers[0][0].x==ereasers[0][1].x&&ereasers[0][0].y==ereasers[0][1].y
      }
    }
    var origin_pointsNew = [];
    for (var i in origin_points) {
      for (var j in origin_points[i]) {
        origin_pointsNew.push(origin_points[i][j]);
      }
    }
    // console.log(ereasers_New); //把所有擦除的点变成一维数组
    // console.log(origin_pointsNew); //把所有原始点变成一维数组
    for (var i in ereasers_New) {
      for (var j in origin_pointsNew) {
        if (ereasers_New[i].x == origin_pointsNew[j].x && ereasers_New[i].y == origin_pointsNew[j].y) {
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          $("#messageInfo").empty();
          $("#messageInfos divs").html('');
          ereasers_New[i] = [];
          assa.push(ereasers_New[i]);
          for (var x in imgInfosList) {
            // console.log(imgInfosList[i])
            if (imgInfosList[x].src == currrentImgSrc) {
              imgInfosList[x].pointInfos.originPoints = [];
              // imgInfosList[x].pointInfos.transparentPoints.push(ereasers_New[i]);
            }
          }
        }
      }
    }
    canvas.removeEventListener('mousemove', onErase, false);

    // Emptying up Pencil Points
    ppts = [];
  }, false);

  var onErase = function() {
    // Saving all the points in an array
    ppts.push({x: mouse.x, y: mouse.y});
    ctx.globalCompositeOperation = 'destination-out';
    // ctx.globalCompositeOperation = 'source-over';
    //新颜色与之前的颜色重叠的部分消失
    ctx.fillStyle = 'rgba(0,0,0,1)';
    ctx.strokeStyle = 'rgba(0,0,0,1)';
    ctx.lineWidth = 1;

    if (ppts.length < 3) {
      var b = ppts[0];
      ctx.beginPath();
      //ctx.moveTo(b.x, b.y);
      //ctx.lineTo(b.x+50, b.y+50);
      ctx.arc(b.x, b.y, ctx.lineWidth / 2, 0, Math.PI * 2, !0);
      ctx.fill();
      ctx.closePath();
      return;
    }
    // Tmp canvas is always cleared up before drawing.
    // ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.moveTo(ppts[0].x, ppts[0].y);

    for (var i = 1; i < ppts.length - 2; i++) {
      var c = (ppts[i].x + ppts[i + 1].x) / 2;
      var d = (ppts[i].y + ppts[i + 1].y) / 2;
      ctx.quadraticCurveTo(ppts[i].x, ppts[i].y, c, d);
    }
    // For the last 2 points
    ctx.quadraticCurveTo(ppts[i].x, ppts[i].y, ppts[i + 1].x, ppts[i + 1].y);
    ctx.stroke();
  };

  //TODO=======显示被擦除之前路径的function========
  function appearOriginPoints() {
    var ctx1 = $("#paint")[0].getContext("2d");
    ctx.globalCompositeOperation = 'source-over';
    ctx1.strokeStyle = "red";
    ctx1.lineWidth = 2;
    ctx1.beginPath();
    ctx1.font = "20px SimSun";
    ctx1.fillStyle = "#333";
    // console.log(points);
    // console.log(CurrrentImgSrc);
    for (var j = 0; j < origin_points.length; j++) {
      for (var i = 0; i < origin_points[j].length; i++) {
        if (i == 0) {
          ctx1.moveTo(origin_points[j][i].x, origin_points[j][i].y);
        } else { //注意是从1开始
          var ctrlP = getCtrlPoint(origin_points[j], i - 1);
          ctx1.bezierCurveTo(ctrlP.pA.x, ctrlP.pA.y, ctrlP.pB.x, ctrlP.pB.y, origin_points[j][i].x, origin_points[j][i].y);
          //ctx.fillText("("+point[i].x+","+point[i].y+")",point[i].x,point[i].y);
        }
      }
    }

    ctx1.stroke();

    function getCtrlPoint(ps, i, a, b) {
      if (!a || !b) {
        a = 0.25;
        b = 0.25;
      }
      //处理两种极端情形
      if (i < 1) {
        var pAx = ps[0].x + (ps[1].x - ps[0].x) * a;
        var pAy = ps[0].y + (ps[1].y - ps[0].y) * a;
      } else {
        var pAx = ps[i].x + (ps[i + 1].x - ps[i - 1].x) * a;
        var pAy = ps[i].y + (ps[i + 1].y - ps[i - 1].y) * a;
      }
      if (i > ps.length - 3) {
        var last = ps.length - 1
        var pBx = ps[last].x - (ps[last].x - ps[last - 1].x) * b;
        var pBy = ps[last].y - (ps[last].y - ps[last - 1].y) * b;
      } else {
        var pBx = ps[i + 1].x - (ps[i + 2].x - ps[i].x) * b;
        var pBy = ps[i + 1].y - (ps[i + 2].y - ps[i].y) * b;
      }
      return {
        pA: {
          x: pAx,
          y: pAy
        },
        pB: {
          x: pBx,
          y: pBy
        }
      }
    }
    //得到点击的坐标
    function getEventPosition(ev) {
      var x,
        y;
      if (ev.layerX || ev.layerX == 0) {
        x = ev.layerX;
        y = ev.layerY;
      } else if (ev.offsetX || ev.offsetX == 0) { //Opera
        x = ev.offsetX;
        y = ev.offsetY;
      }
      return {x: x, y: y};
    }

  }
  function appearTansparentPoints() {
    var context = $("#paint")[0].getContext("2d");
    context.globalCompositeOperation = 'destination-out';
    context.lineWidth = 4;
    var a = newPoints;
    for (var i in a) {
      for (var j in a[i]) {
        // console.log(a[i]);
        context.beginPath();
        context.arc(a[i][j].x, a[i][j].y, context.lineWidth / 2, 0, Math.PI * 2, !0);
        //不关闭路径路径会一直保留下去，当然也可以利用这个特点做出意想不到的效果
        context.closePath();
        context.fillStyle = 'rgba(0,0,0,1)';
        context.fill();
        context.restore();
      }
    }
  }
  //TODO  ======切换的时候找到相应的路径===========
  $('#item0').on('slid.bs.carousel', function() {
    ctx.clearRect(0, 0, tmp_canvas.width, tmp_canvas.height);
    $("#messageInfo").empty();
    $("#Text").val("");
    origin_points = [];
    var Currrent = $(this).children().children(".active").children().attr('src')
    for (var i in imgInfosList) {
      if (imgInfosList[i].src == Currrent) {
        var CurrrentDesc = imgInfosList[i].pointInfos.originPoints;
        for (var v in CurrrentDesc) {
          var newDiv = document.createElement("div");
          $(newDiv).html(CurrrentDesc[v].desc);
          $(newDiv).appendTo($("#messageInfo"));
        }
        var curent_points = imgInfosList[i].pointInfos.originPoints;
        for (var i in curent_points) {
          origin_points.push(curent_points[i].point);
        }
      }
    }
    appearOriginPoints();
  });

}());
